import openpyxl
import csv
from tqdm import tqdm
from pathlib import Path


class JosephRing():
    def __init__(self, people_num, step, death_num,start): 
        self.people_num = people_num
        self.step = step
        self.death_num = death_num
        self.start = start
        self.live_num = people_num - death_num
        self.index = self.start - 1 
        
    def get_state(self):
        persons_state = [True] * self.people_num    #初始化人群的生死状态,Ture表示生，False表示死亡
        death_counter = 0
        step_counter = 0
        index = self.index

        while death_counter < self.death_num:
            if persons_state[self.index]:
                step_counter += 1
                if step_counter == self.step:
                    persons_state[index] = False
                    death_counter += 1
                    step_counter = 0
            index += 1
            index %= self.people_num
        return persons_state
    
    def get_death_order(self):
        index = self.index
        order = [x for x in range(1, self.people_num+1)]
        while self.live_num < len(order):
            index = (self.step + index-1)% len(order)
            yield order[index]
            del order[index]  

def xlsx_read(filename):
    wb = openpyxl.load_workbook(filename)
    sheet = wb.active
    column1= list(sheet.columns)[0][1:]
    column2= list(sheet.columns)[1][1:]
    id_list = []
    name_list = []
    for name in column1:
        name_list.append(name.value)
    for Id in column2:
        id_list.append(Id.value)
        
    return dict(zip(name_list,id_list))
    
def csv_read(filename):
    with open(filename,encoding = 'utf-8-sig') as f:
        fileReader = csv.reader(f)
        fileData = list(fileReader)
    return dict(fileData)

def main():
    filepath = input('请输入文件路径： ')
    file_suffix = Path(filepath).suffix
    if file_suffix == '.csv':
        students_information = csv_read(filepath)
    if file_suffix == '.xlsx':
        students_information = xlsx_read(filepath)
    people_num = len(students_information)
    step = int(input('请输入步长: '))
    assert(step >= 1)
    death_num = int(input('请输入死亡人数: '))
    assert(0 < death_num < people_num)
    start = int(input('请输入初始位置: '))
    assert(0 < start <= people_num)
    jr = JosephRing(people_num, step, death_num,start)
    persons_state = jr.get_state()
    for i in jr.get_death_order():
        print(i)
    for i,student_information in enumerate(tqdm((students_information.items()))):
        if persons_state[i]:
            print(f'第{i+1}位为幸存者,姓名为: {student_information[0]},学号为: {student_information[1]}')
        else:
            print(f'第{i+1}位为牺牲者,姓名为: {student_information[0]},学号为: {student_information[1]}')


if __name__ == '__main__':
    main()